<template>
    <Modal v-model="show" :closable="false" :mask-closable="false" @on-visible-change="showModal" :width="1200">
        <el-card>
            <div slot="header" class="clearfix">
                <span>库存商品信息：</span>
                <el-select style="width: 360px" @clear="clearProduct" @change="changeProduct" clear="item={}" clearable :loading="searchLoading" placeholder="可输入、sku码 进行搜索" filterable remote :remote-method="remoteMethod" v-model="productId">
                    <el-option v-for="(product,ind) in products" :key="ind" :label="product.variationName+','+product.skuCode" :value="product.id">
                        <span style="float: right;color: #8492a6; font-size: 13px">{{product.variationName}}</span>
                        <span style="float: left;">skuCode:{{product.skuCode }}</span>
                    </el-option>
                </el-select>
            </div>
            <template v-if="product && product.productName">
                <div class="st-product-wrap">
                    <img class="st-product-wrap-image" :src="product.pics">
                    <div class="st-product-wrap-info">
                        <div class="st-product-wrap-info-it"> 好友：{{product.toUserId}},{{product.toUserName}}</div>
                        <div class="st-product-wrap-info-it"> 商品名：{{product.productName}}</div>
                        <div class="st-product-wrap-info-it"> 规格属性：{{product.variationName}}</div>
                        <div class="st-product-wrap-info-it"> sku编码：{{product.skuCode}}</div>
                        <div class="st-product-wrap-info-it"> 库存：{{product.stock}}</div>
                    </div>
                </div>
                <el-divider>
                    已绑商品
                </el-divider>
                <el-row class="sku-list" :gutter="10">
                    <el-col v-for="(sku,ind) in product.skus" :span="6" :key="ind">
                        <div v-loading="sku.loading">
                            <h3 class="shop-name">店铺：{{sku.shopName}}</h3>
                            <div class="item-name">
                                商品：{{sku.itemName}}
                            </div>
                            <div class="variation-name">
                                规格：{{sku.variationName}}
                                <i @click="removeLian(sku)" style="margin-top:5px;float: right;font-size: 14px" class="el-icon-delete"></i>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </template>
            <template v-else>
                <div>
                    <span style="color:#f00">请先选择要关联的库存商品</span>
                </div>
            </template>
           
        </el-card>
        <el-card style="margin-top: 10px">
            <div slot="header" class="clearfix">
                <span>平台商品</span>
            </div>
            <el-row>
                <el-col :span="16">
                    <div>
                        <el-form ref="queryParams" inline label-position="top" label-width="80px" v-model="queryParams">
                            <el-form-item>
                                <el-select size="small" @change="search()" v-model="queryParams.shopId" :placeholder="$t('店铺')" style="width: 160px">
                                    <el-option value="">
                                        {{$t('全部店铺')}}
                                    </el-option>
                                    <template v-for="shop in queryShops">
                                        <el-option :value="shop.shopId" :label="shop.shopName+'【'+getShopStatus(shop.status)+'】'" :key="shop.shopId">
                                        </el-option>
                                    </template>
                                </el-select>
                                <el-button icon="el-icon-refresh" size="mini" circle :loading="shopLoading" @click="getAllshop"></el-button>
                            </el-form-item>
                            <el-form-item label="">
                                <el-input size="small" v-model="queryParams.productId" placeholder="商品ID" style="width: 120px" @keyup.enter.native="search()" />
                            </el-form-item>
                            <el-form-item label="">
                                <el-input size="small" v-model="queryParams.name" placeholder="商品标题" style="width: 120px" @keyup.enter.native="search()" />
                            </el-form-item>
                             <el-form-item label="">
                                <el-input size="small" v-model="queryParams.itemSku" placeholder="商品货号" style="width: 120px" @keyup.enter.native="search()" />
                            </el-form-item>
                            <el-form-item>
                                <el-button size="small" v-on:click="search()" type="primary">搜索</el-button>
                                <el-button size="small" v-on:click="reset()">重置</el-button>
                            </el-form-item>
                        </el-form>
                        <ul style="min-height: 100px;" v-loading="loading" class="dtlist">
                            <li v-for="pt in xiapiProducts" :key="pt.id">
                                <div class="st-product-wrap">
                                    <img class="st-product-wrap-image" :src="pt.images[0]">
                                    <div class="st-product-wrap-info">
                                        <h2 style="color:#f00">店铺：{{pt.shopName}}</h2>
                                        <a class="title" target="_blank" :href="genUrl(pt.country, pt.shopId, pt.id)">{{pt.name}}</a>
                                        <div class="tags">
                                            <!--    <el-checkbox size="small" v-for="vara in pt.variations" :label="vara.name" v-model="vara.checked" @change="changeTag" border style="margin-bottom: 10px;"></el-checkbox> -->
                                            <template v-for="vara in pt.variations">
                                                <label v-if="!vara.bindStatus" :class="vara.checked?'is-checked':''" @click="changeTag(pt,vara)">
                                                    <span>{{vara.name}}</span>
                                                </label>
                                                <label v-else class="disabled">
                                                    <el-tooltip class="item" effect="dark" content="已关联了" placement="top-start">
                                                        <span>{{vara.name}}
                                                            <i class="el-icon-circle-check"></i>
                                                        </span>
                                                    </el-tooltip>
                                                </label>
                                            </template>
                                        </div>
                                    </div>
                                </div>
                            </li>
                        </ul>
                        <div style="margin: 10px;overflow: hidden">
                           
<router-link :to="{ path: '/product/shopee/list' }">找不到您的产品,点击同步</router-link>
                            <div style="float: right;">
                                <Page :page-size="page.pageSize" show-total :total="page.total" :current="page.current" @on-change="changePage"></Page>
                            </div>
                        </div>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div style="border: 1px solid #cecece;padding:10px;border-radius: 4px;">
                        <h2 style="border-bottom: 1px solid #cecece;padding:10px 5px">已选商品：<el-button style="float: right;" @click="clearProducts" type="danger" size="small">清空</el-button>
                        </h2>
                        <div>
                            <ul style="min-height: 100px;" class="dtlist">
                                <li v-for="(pt,ind) in selectedProducts" :key="ind">
                                    <div class="st-product-wrap">
                                        <img class="st-product-wrap-image" :src="pt.image">
                                        <div class="st-product-wrap-info">
                                            <h5 style="margin-bottom: 10px">{{pt.itemName}}</h5>
                                            <div class="tags">
                                                <!--    <el-checkbox size="small" v-for="vara in pt.variations" :label="vara.name" v-model="vara.checked" @change="changeTag" border style="margin-bottom: 10px;"></el-checkbox> -->
                                                <label :class="'is-checked'">
                                                    <span>{{pt.variationName}}</span>
                                                </label>
                                            </div>
                                        </div>
                                        <i class="el-icon-delete" @click="removeSelect(pt)" style="font-size:16px;color: #f00;cursor:pointer;"></i>
                                    </div>
                                </li>
                            </ul>
                            <div style="text-align: right;">
                                <el-button type="success" @click="okSubmit" :loading="submitLoading">确认关联</el-button>
                            </div>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </el-card>
        <div slot="footer">
            <el-button size="small" type="success" @click="cancel">关闭</el-button>
        </div>
    </Modal>
</template>
<script>

export default {
    name: 'StorageProduct',
    data() {
        return {
            queryShops:[],
            shopLoading:false,
            submitLoading: false,
            productId: null,
            product: { skus: [] },
            show: false,
            searchLoading: false,
            products: [],
            xiapiProducts: [],
            selectedProducts: [],
            loading: false,
            queryParams: {

            },
            page: {
                total: 0,
                current: 1,
                pageSize: 5
            },
        };
    },
    mounted: function() {



    },
    props: [
        'skuCode'
    ],
    methods: {
        getAllshop: function() {
            var me = this;
            me.shopLoading = true;
            me.$http.post("/xiapishop/getall.do").then(response => {
                var body = response;
                me.shopLoading = false;
                if (body.status == 0) {
                    this.queryShops = body.obj;
                }
            }, response => {
                me.shopLoading = false;
                this.errorMessage("获取店铺失败")
            });
        },
        removeLian: function(sku) {

            var me = this;

            me.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                me.$set(sku, "loading", true);
                me.$http.post("/storageproduct/unbindSku.do", { ids: sku.id }).then(response => {
                    var body = response;
                    if (body.status == 0) {
                        me.product.skus.splice(me.product.skus.indexOf(sku), 1);

                    } else {
                        me.errorMessage(body.info);
                    }
                    me.$set(sku, "loading", false);

                }, response => {
                    me.$set(sku, "loading", false);
                });
            }).catch(() => {

            });



        },
        removeSelect(vari) {
            let me = this;
            me.selectedProducts.splice(me.selectedProducts.indexOf(vari), 1);
            for (var i = 0; i < me.xiapiProducts.length; i++) {
                for (var j = 0; j < me.xiapiProducts[i].variations.length; j++) {

                    if (vari.itemId == me.xiapiProducts[i].id && vari.variationId == me.xiapiProducts[i].variations[j]['variation_id']) {

                        me.$set(me.xiapiProducts[i].variations[j], "checked", false);
                        return;
                    }

                }

            }

        },
        changeTag(prt, vari) {

            vari.checked = !vari.checked;
            if (vari.checked) {

                this.selectedProducts.push({
                    variationId: vari.variation_id,
                    variationName: vari.name,
                    itemId: prt.id,
                    image: prt.images[0],
                    itemName: prt.name
                });
            } else {
                var tp = null;
                for (var i = 0; i < this.selectedProducts.length; i++) {
                    tp = this.selectedProducts[i];
                    if (tp.variationId == vari.variation_id && tp.itemId == prt.id) {
                        break;
                    }
                    tp = null;
                }
                if (tp) {
                    this.selectedProducts.splice(this.selectedProducts.indexOf(tp), 1);
                }

            }
        },
        search: function() {
            this.page.current = 1;
            this.page.total = 0;
            this.getList();
        },
        reset: function() {
            this.queryParams = {};
            this.search();
        },
        changePage(current) {
            this.page.current = current;
            this.getList();
        },
        clearProducts: function() {
            let me = this;
            me.selectedProducts = [];
            for (var i = 0; i < me.xiapiProducts.length; i++) {
                for (var j = 0; j < me.xiapiProducts[i].variations.length; j++) {
                    me.$set(me.xiapiProducts[i].variations[j], "checked", false);
                }

            }
        },
        remoteMethod(query, state) {
            if (query == '') {
                this.searchLoading = false;
                return false;
            }
            var me = this;
            me.searchLoading = true;
            me.$http.post("/storageproduct/shareSearch.do", { name: query }).then(response => {
                var body = response;
                if (body.status == 0) {
                    me.products = body.obj;
                    if (state && me.products.length == 1) {
                        this.productId = me.products[0].id;
                        this.changeProduct(this.productId);
                    }
                }
                me.searchLoading = false;

            }, response => {
                me.searchLoading = false;
            });

        },
        clearProduct() {

            for (var i = 0; i < this.xiapiProducts.length; i++) {
                for (var j = 0; j < this.xiapiProducts[i].variations.length; j++) {
                    this.$set(this.xiapiProducts[i].variations[j], "checked", false);
                    this.$set(this.xiapiProducts[i].variations[j], "bindStatus", false);
                }

            }
            this.product = { skus: [] };

        },
        changeProduct(pr) {

            var me = this;
            if (!pr) return;
            me.products.forEach((dt, ind) => {

                if (pr == dt.id) {
                    me.product = dt;
                }
            });
            this.getDetail();
        },
        getList: function() {
            var me = this;
            var params = me.queryParams;
            params.current = me.page.current;
            params.pageSize = me.page.pageSize;
            me.loading = true;
            me.$http.post("/xiapiproduct/getList.do", params).then(response => {
                var body = response;
                if (body.status == 0) {
                    me.page.total = body.obj.totalCount;
                    me.xiapiProducts = body.obj.list;
                    for (var i = 0; i < me.xiapiProducts.length; i++) {
                        me.$set(me.xiapiProducts[i], "images", JSON.parse(me.xiapiProducts[i]['images']))
                        me.$set(me.xiapiProducts[i], "variations", JSON.parse(me.xiapiProducts[i]['variations']));
                        if (me.xiapiProducts[i].variations.length <= 0) {
                            me.xiapiProducts[i].variations.push({
                                variation_id: 0,
                                name: "默认款"
                            });
                        }

                        for (var j = 0; j < me.xiapiProducts[i].variations.length; j++) {


                            for (var k = 0; k < me.selectedProducts.length; k++) {
                                let tp = me.selectedProducts[k];
                                if (tp.variationId == me.xiapiProducts[i].variations[j].variation_id && tp.itemId == me.xiapiProducts[i].id) {
                                    me.$set(me.xiapiProducts[i].variations[j], "checked", true);
                                    break;
                                } else {
                                    me.$set(me.xiapiProducts[i].variations[j], "checked", false);
                                }
                            }

                        }

                    }
                    this.bindSku();

                }
                me.loading = false;
            }, response => {
                me.loading = false;
            });
        },
        showDialog() {
            this.show = true;
        },
        showModal(val) {
            if (val) {
                if (this.skuCode) {
                    this.remoteMethod(this.skuCode, true);
                }
            } else {
                this.product = { sku: [] };
                this.products = [];
                this.productId = null;
                this.xiapiProducts = [];
                this.selectedProducts = [];
            }
        },
        getDetail() {
            this.showLoading();
            this.$http.post("/storageproduct/show_" + this.product.id + ".do", {

            }).then(response => {
                this.hideLoading();
                if (response.status == 0) {
                    this.product = response.obj;
                    this.bindSku();
                }

            }, response => {
                this.hideLoading();
            });
        },
        bindSku: function() {
            var me = this;
            for (var i = 0; i < me.xiapiProducts.length; i++) {

                var itemProduct = me.xiapiProducts[i];
                var variations = itemProduct.variations;
                for (var j = 0; j < variations.length; j++) {
                    me.$set(variations[j], "bindStatus", false);
                    for (var m = 0; m < me.product.skus.length; m++) {
                        let tp = me.product.skus[m];
                        if (tp.variationId == variations[j].variation_id && tp.itemId == itemProduct.id) {
                            me.$set(variations[j], "bindStatus", true);
                            break;
                        } else {
                            me.$set(variations[j], "bindStatus", false);
                        }
                    }

                }

            }
        },
        cancel: function() {
            this.show = false;
            this.$emit("cancel");
        },
        okSubmit: function() {
            if (!this.product || !this.product.id) {

                this.errorMessage("请先选择要关联的库存商品")
                return;
            }
            if (this.selectedProducts.length <= 0) {
                this.errorMessage("请先选择要关联的平台商品")
                return;
            }
            let itemIds = [];
            let variationIds = [];
            for (var i = 0; i < this.selectedProducts.length; i++) {
                itemIds.push(this.selectedProducts[i].itemId);
                variationIds.push(this.selectedProducts[i].variationId);
            }
            this.submitLoading = true;
            this.$http.post("/storageproduct/bindSku.do", {
                productId: this.product.id,
                itemIds: itemIds.join(","),
                variationIds: variationIds.join(",")
            }).then(response => {
                this.submitLoading = false;
                if (response.status == 0) {
                    this.clearProducts();

                    this.successMessage("绑定成功");
                    this.getDetail();
                } else {
                    this.errorMessage(response.info);
                }
            }, response => {
                this.submitLoading = false;
                this.errorMessage("系统异常");
            });
        }
    }
}
</script>
<style scoped>
.st-product-wrap {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-direction: row;
    flex-direction: row;

}

.st-product-wrap-image {
    width: 120px;
    height: 120px;
    margin-right: 10px;
}

.st-product-wrap-info-it {
    line-height: 30px;
    font-size: 15px;
}

a.title {
    font-size: 14px;
    margin-bottom: 10px;
    display: block;
}

.dtlist li {
    list-style: none;
    margin-bottom: 10px;
    padding: 10px;
    border-bottom: 1px dotted #cecece;
}

.tags>label {
    padding: 5px 9px;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
    color: #606266;
    font-weight: 500;
    font-size: 14px;
    position: relative;
    cursor: pointer;
    display: inline-block;
    white-space: nowrap;
    box-sizing: border-box;
    line-height: normal;
    margin-right: 10px;
    margin-bottom: 10px;
}

.tags>label span {
    display: inline-block;
    padding: 2px 5px;
    line-height: 19px;
    font-size: 14px;
}

.tags>label.is-checked {
    border-color: #409eff;
    color: #409eff;
}

.tags>label.disabled {
    border-color: #67c23a;
    color: #67c23a;
}

.sku-list {}

.sku-list .el-col {


    list-style: none;
    margin-bottom: 10px;

}

.sku-list .el-col>div {
    border-radius: 5px;
    padding: 5px 10px;
    border: 1px solid #67c23a;
}

.sku-list .el-col .item-name {
    font-size: 14px;
    margin-bottom: 10px;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
}

.sku-list .el-col .variation-name {
    font-size: 14px;
    color: #f00;
    margin-bottom: 10px;
}

.sku-list .el-col .shop-name {
    font-size: 16px;
    color: #f00;
    margin-bottom: 10px;
}
</style>